#include <QDebug>
#include <QRegularExpression>  
#include "vlineedit.h"

VLineEdit::VLineEdit(QWidget *parent)
	: QLineEdit(parent)
{
	resize(220, 40);
    setAlignment(Qt::AlignHCenter);
    setFont(QFont("微软雅黑", 10));
    setDefaultStyleSheet();
}

VLineEdit::~VLineEdit()
{}

void VLineEdit::setMode(ECHOMODE echoMode)
{
    switch (echoMode)
    {
    case ECHOMODE::REVISE_PASSWORD:passwordMode(); break;
    case ECHOMODE::REGIST_ACCOUNT:accountMode(); break;
    case ECHOMODE::REGIST_PASSWORD:passwordMode(); break;
    case ECHOMODE::LOGIN_PASSWORD:setEchoMode(QLineEdit::Password); break;
    }
}


void VLineEdit::accountMode()
{
    connect(this, &VLineEdit::textChanged, this, &VLineEdit::onAccountEditTextChanged);
}

void VLineEdit::passwordMode()
{
    setEchoMode(QLineEdit::Password);
    connect(this, &VLineEdit::textChanged, this, &VLineEdit::onPasswordEditTextChanged);
}

void VLineEdit::onAccountEditTextChanged(const QString& text)
{
    QSet<ERRORTYPE>errorExist;
    QRegularExpression regex("^\\d+$"); // 匹配从开始到结束都是数字的字符串  正则表达式

    if (!regex.match(text).hasMatch())
        errorExist.insert(ERRORTYPE::ACCOUNT_ONLY_NUMBER);
    if (text.size() < 8 || text.size() >= 16)
        errorExist.insert(ERRORTYPE::ACCOUNT_LENGTH);
    emit formatError(errorExist);

    if (errorExist.empty())setDefaultStyleSheet();
    else setErrorPromptStyleSheet();
}

void VLineEdit::onPasswordEditTextChanged(const QString& text)
{
    QSet<ERRORTYPE>errorExist;
    QRegularExpression regex("^[a-zA-Z0-9.]+$");
    if (!regex.match(text).hasMatch())
        errorExist.insert(ERRORTYPE::PASSWORD_CONTAIN_SPECIAL_CHAR);
        
    if (text.size() < 8 || text.size() >= 16)
        errorExist.insert(ERRORTYPE::PASSWORD_LENGTH);
        
    emit formatError(errorExist);

    if (errorExist.empty())setDefaultStyleSheet();
    else setErrorPromptStyleSheet();
}

void VLineEdit::setDefaultStyleSheet()
{
    setStyleSheet(R"(
        VLineEdit
        {
            background-color:#F0FFFF;
            border:none;
            border-radius: 4px; 
        }
     )");
}

void VLineEdit::setErrorPromptStyleSheet()
{
    setStyleSheet(R"(
		VLineEdit
		{
			background-color:#F0FFFF;
			border-style: solid;
			border-width: 1px;
			border-color: red;
			border-radius: 4px; 
		}
	)");
}